package com.sortingalgorithm;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibFactory implements MethodInterceptor {

    private Object target;

    public CglibFactory(Object target) {
        this.target = target;
    }

    public Object getCglibInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Class clazz = target.getClass();
        Method m;
        // 得到对应的方法
        if(objects == null){
            m = getClass().getMethod(method.getName());
        }else{
            Class [] methodArgs = new Class[objects.length];
            for (int i = 0;i < methodArgs.length;i++){
                methodArgs[i] = objects[i].getClass();
            }
            m = clazz.getMethod(method.getName(),methodArgs);
        }
        CalculateRuntime cr = m.getAnnotation(CalculateRuntime.class);
        if(cr != null){
            long start = System.currentTimeMillis();
            Object res = method.invoke(target,objects);
            long end = System.currentTimeMillis();
            System.out.println(method.getName() +":的运行时间为：" +(end - start) );
            return res;
        }
        return method.invoke(target,objects);

    }
}
